﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.SimulationPerformanceRecorder.CApSimulationPerformanceRecorderManager
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Implementation.ModelObjects;


namespace DnProcessSimulateCommands.SimulationPerformanceRecorder;

internal class CApSimulationPerformanceRecorderManager
{
  private long m_intervalSampling;
  private double m_nextTimeToStop;
  private long CAST_TO_MB = 1048576 /*0x100000*/;
  private DateTime m_start;
  private string m_samplingLogFileLocation;
  private bool m_performanceActivate;
  private TxSimulationPlayer m_simulationPlayer;
  private static CApSimulationPerformanceRecorderManager instance;
  private bool m_processHeapMemoryConsumption = true;

  private CApSimulationPerformanceRecorderManager()
  {
    this.m_intervalSampling = 100L;
    this.m_samplingLogFileLocation = "c:\\SimulationRecordings\\simulationPerformance.csv";
    this.PerformanceActivate = false;
    this.ProcessHeapMemoryConsumption = true;
  }

  public static CApSimulationPerformanceRecorderManager Instance
  {
    get
    {
      if (CApSimulationPerformanceRecorderManager.instance == null)
        CApSimulationPerformanceRecorderManager.instance = new CApSimulationPerformanceRecorderManager();
      return CApSimulationPerformanceRecorderManager.instance;
    }
  }

  public bool ProcessHeapMemoryConsumption
  {
    get => this.m_processHeapMemoryConsumption;
    set => this.m_processHeapMemoryConsumption = value;
  }

  public string SamplingLogFileLocation
  {
    get => this.m_samplingLogFileLocation;
    set => this.m_samplingLogFileLocation = value;
  }

  public long IntervalSampling
  {
    get => this.m_intervalSampling;
    set => this.m_intervalSampling = value;
  }

  public bool PerformanceActivate
  {
    get => this.m_performanceActivate;
    set => this.m_performanceActivate = value;
  }

  public void SetPerformanceRecorderMode()
  {
    if (this.m_performanceActivate)
    {
      this.RegisterSimulationEvents();
      Process currentProcess = Process.GetCurrentProcess();
      long num1 = 0;
      long num2 = 0;
      if (this.ProcessHeapMemoryConsumption)
        TxPerformanceMeasurementEx.GetProcessHeapMemoryConsumption(ref num1, ref num2);
      using (StreamWriter streamWriter = File.AppendText(this.m_samplingLogFileLocation))
      {
        streamWriter.WriteLine("");
        streamWriter.WriteLine("");
        string fileVersion = currentProcess.MainModule.FileVersionInfo.FileVersion;
        string empty = string.Empty;
        string str = !this.CheckBetaCollisionDetector() ? "TCD" : "KCD";
        this.m_simulationPlayer = TxApplication.ActiveDocument.SimulationPlayer;
        double num3 = 0.0;
        if (this.m_simulationPlayer != null)
          num3 = this.m_simulationPlayer.CurrentTime;
        streamWriter.WriteLine("Run data on Tecnomatix {0} Collision Detection {1} Simulation Speed {2}", (object) fileVersion, (object) str, (object) TxApplication.Options.Simulation.SimulationSpeed);
        streamWriter.WriteLine("start at {0}", (object) DateTime.Now);
        streamWriter.WriteLine("Event type,Simulation time,            ,Real Time,          Percentage     ,WorkingSet,PagedMemory,HeapMemoryUsed");
        streamWriter.WriteLine("          ,      Start    ,    End     ,     CPU ,SamplingInterval/RealTime,     (Mb) ,   (Mb)    ,     (Mb)");
        streamWriter.WriteLine("Activate Performance , {0}, , , ,{1},{2},{3}", (object) num3, (object) (currentProcess.WorkingSet64 / this.CAST_TO_MB), (object) (currentProcess.PagedMemorySize64 / this.CAST_TO_MB), (object) (num2 / this.CAST_TO_MB));
      }
    }
    else
      this.UnregisterSimulationEvents();
  }

  private void RegisterSimulationEvents()
  {
    this.m_simulationPlayer = TxApplication.ActiveDocument.SimulationPlayer;
    this.m_simulationPlayer.TimeIntervalReached += new TxSimulationPlayer_TimeIntervalReachedEventHandler(this.m_simulation_TimeIntervalReached);
    this.m_simulationPlayer.SimulationStopped += new TxSimulationPlayer_SimulationStoppedEventHandler(this.m_simulationPlayer_SimulationStopped);
    this.m_simulationPlayer.SimulationEndedForward += new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.m_simulationPlayer_SimulationEndedForward);
    this.m_simulationPlayer.SimulationStartedForward += new TxSimulationPlayer_SimulationStartedForwardEventHandler(this.m_simulationPlayer_SimulationStarted);
    this.m_simulationPlayer.SimulationCleared += new TxSimulationPlayer_SimulationClearedEventHandler(this.m_simulationPlayer_SimulationCleared);
  }

  private void UnregisterSimulationEvents()
  {
    this.m_simulationPlayer = TxApplication.ActiveDocument.SimulationPlayer;
    this.m_simulationPlayer.TimeIntervalReached -= new TxSimulationPlayer_TimeIntervalReachedEventHandler(this.m_simulation_TimeIntervalReached);
    this.m_simulationPlayer.SimulationStopped -= new TxSimulationPlayer_SimulationStoppedEventHandler(this.m_simulationPlayer_SimulationStopped);
    this.m_simulationPlayer.SimulationEndedForward -= new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.m_simulationPlayer_SimulationEndedForward);
    this.m_simulationPlayer.SimulationStartedForward -= new TxSimulationPlayer_SimulationStartedForwardEventHandler(this.m_simulationPlayer_SimulationStarted);
    this.m_simulationPlayer.SimulationCleared -= new TxSimulationPlayer_SimulationClearedEventHandler(this.m_simulationPlayer_SimulationCleared);
  }

  private void m_simulation_TimeIntervalReached(
    object sender,
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    if (!TxDoubleExtension.IsGreaterThan(args.CurrentTime, this.m_nextTimeToStop, 1E-07))
      return;
    double nextTimeToStop = this.m_nextTimeToStop;
    double num1 = nextTimeToStop - (double) this.m_intervalSampling;
    this.m_nextTimeToStop += (double) this.m_intervalSampling;
    DateTime now = DateTime.Now;
    TimeSpan timeSpan = now - this.m_start;
    this.m_start = now;
    Process currentProcess = Process.GetCurrentProcess();
    long num2 = 0;
    long num3 = 0;
    if (this.ProcessHeapMemoryConsumption)
      TxPerformanceMeasurementEx.GetProcessHeapMemoryConsumption(ref num2, ref num3);
    using (StreamWriter streamWriter = File.AppendText(this.m_samplingLogFileLocation))
      streamWriter.WriteLine("Time interval ({7}),  {0},{1},{2},{3}%,{4},{5},{6}", (object) num1.ToString("F01"), (object) nextTimeToStop.ToString("F01"), (object) timeSpan.TotalSeconds.ToString("F01"), (object) ((double) (this.m_intervalSampling * 100L) / timeSpan.TotalSeconds).ToString("F01"), (object) (currentProcess.WorkingSet64 / this.CAST_TO_MB), (object) (currentProcess.PagedMemorySize64 / this.CAST_TO_MB), (object) (num3 / this.CAST_TO_MB), (object) TxApplication.ActiveDocument.SimulationPlayer.TimeInterval);
  }

  private void m_simulationPlayer_SimulationEndedForward(
    object sender,
    TxSimulationPlayer_SimulationEndedForwardEventArgs args)
  {
  }

  private void m_simulationPlayer_SimulationStopped(
    object sender,
    TxSimulationPlayer_SimulationStoppedEventArgs args)
  {
  }

  private void m_simulationPlayer_SimulationStarted(
    object sender,
    TxSimulationPlayer_SimulationStartedForwardEventArgs args)
  {
    this.m_start = DateTime.Now;
    this.m_nextTimeToStop = TxApplication.ActiveDocument.SimulationPlayer.CurrentTime + (double) this.m_intervalSampling;
  }

  private void m_simulationPlayer_SimulationCleared(
    object sender,
    TxSimulationPlayer_SimulationClearedEventArgs args)
  {
  }

  public bool CheckBetaCollisionDetector()
  {
    string valueData = string.Empty;
    return (this.getRegistryStringValue(Registry.LocalMachine, TxGeneralAppUtil.GetRegistryPath() + "\\TUNE\\NewAssembler\\Startup Objects\\02", "Class ID", out valueData) || this.getRegistryStringValue(Registry.LocalMachine, TxGeneralAppUtil.GetRegistryPath() + "\\TUNE\\NewAssemblerTC\\Startup Objects\\02", "Class ID", out valueData) || this.getRegistryStringValue(Registry.LocalMachine, TxGeneralAppUtil.GetRegistryPath() + "\\TUNE\\NewViewer\\Startup Objects\\02", "Class ID", out valueData) || this.getRegistryStringValue(Registry.LocalMachine, TxGeneralAppUtil.GetRegistryPath() + "\\TUNE\\Viewer\\Startup Objects\\02", "Class ID", out valueData)) && valueData == "{CABA1CDF-75B0-4494-907E-38CA4F889FB3}";
  }

  public bool getRegistryStringValue(
    RegistryKey regType,
    string keyName,
    string valueName,
    out string valueData)
  {
    bool registryStringValue = false;
    valueData = "";
    try
    {
      RegistryKey registryKey = regType.OpenSubKey(keyName);
      if (registryKey != null)
      {
        valueData = registryKey.GetValue(valueName).ToString();
        registryStringValue = true;
      }
    }
    catch (Exception ex)
    {
      ex.ToString();
      registryStringValue = false;
    }
    return registryStringValue;
  }
}
